//
//  ConversationListDataSource.swift
//  Mixin
//
//  Created by zhanghanbing on 2018/8/29.
//  Copyright © 2018年 Insight. All rights reserved.
//

import RxSwift

class ConversationListDataSource {
    
    private(set) var chats: Results<OCTChat>!
    fileprivate var chatsToken: RLMNotificationToken?
    fileprivate let friends: Results<OCTFriend>
    fileprivate var friendsToken: RLMNotificationToken?
    
    let tableView: UITableView
    
    init(tableView: UITableView) {
        self.tableView = tableView
        
        let submanagerObjects = ToxManager.shared.toxMananger!.objects
        
        self.chats = submanagerObjects.chats().sortedResultsUsingProperty("lastActivityDateInterval", ascending: false)
        self.friends = submanagerObjects.friends()
        print("chats: \(chats.count)")
        
        addNotificationBlocks()
    }
    
    private func addNotificationBlocks() {
        chatsToken = chats.addNotificationBlock { [unowned self] change in
            switch change {
            case .initial:
                break
            case .update(_, let deletions, let insertions, let modifications):
                self.tableView.beginUpdates()
                self.tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) },
                                          with: .automatic)
                self.tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) },
                                          with: .automatic)
                self.tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) },
                                          with: .none)
                self.tableView.endUpdates()
            case .error(let error):
                fatalError("\(error)")
            }
        }
    }
    
    deinit {
        chatsToken?.invalidate()
        friendsToken?.invalidate()
    }
}

extension OCTSubmanagerUser {
    func toUserItem() -> UserItem {
        let model = UserItem(userId: publicKey, fullName: userName() ?? "", identityNumber: "", avatarUrl: "", phone: nil, isVerified: true, muteUntil: nil, appId: nil, createdAt: nil, relationship: "", role: "", appDescription: nil, appCreatorId: nil)
        return model
    }
}

extension OCTChat {
//    func toConversationItem() -> ConversationItem {
//        let userItem = ToxManager.shared.toxMananger!.user.toUserItem()
//        let model = ConversationItem.init(ownerUser: userItem)
//        model.ownerFullName = userItem.fullName
//        model.ownerIdentityNumber = "\(userItem.fullName.hashValue % 24)"
//        model.category = ConversationCategory.CONTACT.rawValue
//        if let lastMessage = lastMessage() {
//            model.content = lastMessage.0
//            model.contentType = lastMessage.1
//        }
//        model.chat = self
//        return model
//    }
    
    func lastMessage() -> (String, String, Bool)? {
//        let category = item.contentType
//        messageTypeImageView.image = MessageCategory.iconImage(forMessageCategoryString: category)
//        messageTypeImageView.isHidden = (messageTypeImageView.image == nil)
//        if category.hasSuffix("_TEXT") {
//            if item.isGroup() {
//                contentLabel.text = "\(senderName): \(item.content)"
//            } else {
//                contentLabel.text = item.content
//            }
//        } else if category.hasSuffix("_IMAGE") {
//            if item.isGroup() {
//                contentLabel.text = "\(senderName): \(Localized.NOTIFICATION_CONTENT_PHOTO)"
//            } else {
//                contentLabel.text = Localized.NOTIFICATION_CONTENT_PHOTO
//            }
//        } else if category.hasSuffix("_STICKER") {
//            if item.isGroup() {
//                contentLabel.text = "\(senderName): \(Localized.NOTIFICATION_CONTENT_STICKER)"
//            } else {
//                contentLabel.text = Localized.NOTIFICATION_CONTENT_STICKER
//            }
//        } else if category.hasSuffix("_CONTACT") {
//            if item.isGroup() {
//                contentLabel.text = "\(senderName): \(Localized.NOTIFICATION_CONTENT_CONTACT)"
//            } else {
//                contentLabel.text = Localized.NOTIFICATION_CONTENT_CONTACT
//            }
//        } else if category.hasSuffix("_DATA") {
//            if item.isGroup() {
//                contentLabel.text = "\(senderName): \(Localized.NOTIFICATION_CONTENT_FILE)"
//            } else {
//                contentLabel.text = Localized.NOTIFICATION_CONTENT_FILE
//            }
//        } else if category.hasSuffix("_VIDEO") {
//            if item.isGroup() {
//                contentLabel.text = "\(senderName): \(Localized.NOTIFICATION_CONTENT_VIDEO)"
//            } else {
//                contentLabel.text = Localized.NOTIFICATION_CONTENT_VIDEO
//            }
//        } else if category.hasSuffix("_AUDIO") {
        guard let message = lastMessage else {
            return nil
        }
        
        if let text = message.messageText {
            return (text.text ?? "", "_TEXT", text.isDelivered)
        }
        else if let file = message.messageFile {
            let fileName = file.fileName ?? ""
            return (fileName, "_IMAGE", file.fileType == OCTMessageFileType.ready) //String(localized: message.isOutgoing() ? "chat_outgoing_file" : "chat_incoming_file") + " \(fileName)"
        }
//        else if let call = message.messageCall {
//            switch call.callEvent {
//            case .answered:
//                let timeString = call.callDuration//String(timeInterval: call.callDuration)
//                return "\(timeString)"
//            case .unanswered:
//                return message.isOutgoing() ? "chat_unanwered_call" : "chat_missed_call_message"
//            }
//        }
        
        return nil
    }
}
